﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Hmc.IM.Common.UserControls
{
    public partial class ucIPTextBox : UserControl, IValidate
    {
        /// <summary> 
        /// 边框颜色 
        /// </summary> 
        private Color _BorderColor = Color.FromArgb(219, 224, 230);
        /// <summary> 
        /// 边框颜色 
        /// </summary> 
        [Category("外观"),
       Description("获得或设置控件的边框颜色"),
       DefaultValue(typeof(Color), "219, 224, 230")]
        public Color BorderColor
        {
            get { return _BorderColor; }
            set { _BorderColor = value; }
        }

        /// <summary> 
        /// 热点边框颜色 
        /// </summary> 
        private Color _HotColor = Color.FromArgb(0x33, 0x5E, 0xA8);

        /// <summary> 
        /// 是否鼠标MouseOver状态 
        /// </summary> 
        private bool _IsMouseOver = false;

        /// <summary>
        /// tip 值
        /// </summary>
        public string ToolTipText
        {
            get
            { return this.toolTip1.GetToolTip(Box1); }
            set
            {
                this.toolTip1.SetToolTip(Box1, value);
                this.toolTip1.SetToolTip(Box2, value);
                this.toolTip1.SetToolTip(Box3, value);
                this.toolTip1.SetToolTip(Box4, value);
                this.toolTip1.SetToolTip(label1, value);
                this.toolTip1.SetToolTip(label2, value);
                this.toolTip1.SetToolTip(label3, value);
            }
        }

        /// <summary>
        /// 值
        /// </summary>
        public override string Text
        {
            get
            {
                return Box1.Text + "." + Box2.Text + "." + Box3.Text + "." + Box4.Text;
            }
            set
            {
                if (value != "" && value != null)
                {
                    string[] pieces = new string[4];
                    pieces = value.ToString().Split(".".ToCharArray(), 4);
                    Box1.Text = pieces[0];
                    Box2.Text = pieces[1];
                    Box3.Text = pieces[2];
                    Box4.Text = pieces[3];
                }
                else
                {
                    Box1.Text = "";
                    Box2.Text = "";
                    Box3.Text = "";
                    Box4.Text = "";
                }
            }
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        public bool IsValid()
        {
            try
            {
                int checkval = int.Parse(Box1.Text);
                if (checkval < 0 || checkval > 255)
                    return false;
                checkval = int.Parse(Box2.Text);
                if (checkval < 0 || checkval > 255)
                    return false;
                checkval = int.Parse(Box3.Text);
                if (checkval < 0 || checkval > 255)
                    return false;
                checkval = int.Parse(Box4.Text);
                if (checkval < 0 || checkval > 255)
                    return false;
                else
                    return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public ucIPTextBox()
        {
            InitializeComponent();
            panel1.Paint += new PaintEventHandler(panel1_Paint);
        }

        /// <summary>
        /// 重新绘制边框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void panel1_Paint(object sender, PaintEventArgs e)
        {
            System.Drawing.Pen pen;
            if (!this._IsMouseOver)
                //边框Width为1个像素 
                pen = new Pen(this._BorderColor, 1);
            else
                pen = new Pen(this._HotColor, 1);
            //绘制边框 
            using (Graphics g = e.Graphics)
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
                pen.Dispose();
                g.Dispose();
            }
        }

        private bool IsValid(string inString)
        {
            try
            {
                int theValue = int.Parse(inString);
                if (theValue >= 0 && theValue <= 255)
                    return true;
                else
                {
                    MessageBox.Show("IP地址范围在0~255之间", "消息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 第一节验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Box1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar.ToString() == "." || Char.IsDigit(e.KeyChar) || e.KeyChar == 8)
            {
                if (e.KeyChar.ToString() == ".")
                {
                    if (Box1.Text != "" && Box1.Text.Length != Box1.SelectionLength)
                    {
                        if (IsValid(Box1.Text))
                            Box2.Focus();
                        else
                            Box1.SelectAll();
                    }
                    e.Handled = true;
                }

                else if (Box1.SelectionLength != Box1.Text.Length)
                {
                    if (Box1.Text.Length == 2)
                    {
                        if (e.KeyChar == 8)
                            Box1.Text.Remove(Box1.Text.Length - 1, 1);
                        else if (!IsValid(Box1.Text + e.KeyChar.ToString()))
                        {
                            Box1.SelectAll();
                            e.Handled = true;
                        }
                        else
                        {
                            Box2.Focus();
                        }
                    }
                }
            }
            else
                e.Handled = true;
        }

        /// <summary>
        /// 第二节验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Box2_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar.ToString() == "." || Char.IsDigit(e.KeyChar) || e.KeyChar == 8)
            {
                if (e.KeyChar.ToString() == ".")
                {
                    if (Box2.Text != "" && Box2.Text.Length != Box2.SelectionLength)
                    {
                        if (IsValid(Box1.Text))
                            Box3.Focus();
                        else
                            Box2.SelectAll();
                    }
                    e.Handled = true;
                }
                else if (Box2.SelectionLength != Box2.Text.Length)
                {
                    if (Box2.Text.Length == 2)
                    {
                        if (e.KeyChar == 8)
                        {
                            Box2.Text.Remove(Box2.Text.Length - 1, 1);
                        }
                        else if (!IsValid(Box2.Text + e.KeyChar.ToString()))
                        {
                            Box2.SelectAll();
                            e.Handled = true;
                        }
                        else
                        {
                            Box3.Focus();
                        }
                    }
                }
                else if (Box2.Text.Length == 0 && e.KeyChar == 8)
                {
                    Box1.Focus();
                    Box1.SelectionStart = Box1.Text.Length;
                }
            }
            else
                e.Handled = true;

        }

        /// <summary>
        /// 第三节验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Box3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar.ToString() == "." || Char.IsDigit(e.KeyChar) || e.KeyChar == 8)
            {
                if (e.KeyChar.ToString() == ".")
                {
                    if (Box3.Text != "" && Box3.SelectionLength != Box3.Text.Length)
                    {
                        if (IsValid(Box1.Text))
                            Box4.Focus();
                        else
                            Box3.SelectAll();
                    }
                    e.Handled = true;
                }
                else if (Box3.SelectionLength != Box3.Text.Length)
                {
                    if (Box3.Text.Length == 2)
                    {
                        if (e.KeyChar == 8)
                        {
                            Box3.Text.Remove(Box3.Text.Length - 1, 1);
                        }
                        else if (!IsValid(Box3.Text + e.KeyChar.ToString()))
                        {
                            Box3.SelectAll();
                            e.Handled = true;
                        }
                        else
                        {
                            Box4.Focus();
                        }
                    }
                }
                else if (Box3.Text.Length == 0 && e.KeyChar == 8)
                {
                    Box2.Focus();
                    Box2.SelectionStart = Box2.Text.Length;
                }
            }
            else
                e.Handled = true;
        }

        /// <summary>
        /// 第四节验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Box4_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == 8)
            {
                if (Box4.SelectionLength != Box4.Text.Length)
                {
                    if (Box4.Text.Length == 2)
                    {
                        if (e.KeyChar == 8)
                        {
                            Box4.Text.Remove(Box4.Text.Length - 1, 1);
                        }
                        else if (!IsValid(Box4.Text + e.KeyChar.ToString()))
                        {
                            Box4.SelectAll();
                            e.Handled = true;
                        }
                    }
                }
                else if (Box4.Text.Length == 0 && e.KeyChar == 8)
                {
                    Box3.Focus();
                    Box3.SelectionStart = Box3.Text.Length;
                }
            }
            else
                e.Handled = true;
        }

        private void Box_Enter(object sender, System.EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            tb.SelectAll();
        }

        private void label_EnabledChanged(object sender, System.EventArgs e)
        {
            Label lbl = (Label)sender;
            if (lbl.Enabled)
                lbl.BackColor = SystemColors.Window;
            else
                lbl.BackColor = SystemColors.Control;
        }

        private void panel1_EnabledChanged(object sender, System.EventArgs e)
        {
            Panel pan = (Panel)sender;
            if (pan.Enabled)
                pan.BackColor = SystemColors.Window;
            else
                pan.BackColor = SystemColors.Control;
        }

        /// <summary>
        /// 绘制边框
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            //只有在边框样式为FixedSingle时自定义边框样式才有效 
            if (this.BorderStyle == BorderStyle.FixedSingle)
            {
                System.Drawing.Pen pen;

                //边框Width为1个像素 
                pen = new Pen(this._BorderColor, 1); ;
                //绘制边框 
                using (Graphics g = e.Graphics)
                {
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.DrawRectangle(pen, 1, 1, this.Width - 1, this.Height - 1);
                    pen.Dispose();
                }
            }
        }

        private void ucIPTextBox_Enter(object sender, EventArgs e)
        {
            this._IsMouseOver = true;
        }

        private void ucIPTextBox_Leave(object sender, EventArgs e)
        {
            this._IsMouseOver = false;
        }

        #region 验证接口的实例

        /// <summary>
        /// 错误提示信息
        /// </summary>
        ucErrorProvider errorInfo = new ucErrorProvider();

        private bool isAllowEmpty = true;

        /// <summary>
        /// 设置是否允许为空
        /// </summary>
        [Browsable(true), Category("验证"), DefaultValue(true), Description("设置控件的值是否允许为空")]
        public bool IsAllowEmpty
        {
            get { return isAllowEmpty; }
            set { isAllowEmpty = value; }
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        public new bool Validate()
        {
            errorInfo.Clear();
            if (!this.IsAllowEmpty)
            {
                if ((this.Box1.Text.Trim() == string.Empty) || (this.Box2.Text.Trim() == string.Empty) || (this.Box3.Text.Trim() == string.Empty) || this.Box4.Text.Trim() == string.Empty)
                {
                    errorInfo.SetError(this, "该项不能为空！");
                    return this.IsValidated = false;
                }
            }
            if ((this.Expression != null) && (this.Expression.Trim() != string.Empty)
                && (!Regex.IsMatch(this.Text, this.Expression)))
            {
                errorInfo.SetError(this, this.SetError);
                return this.IsValidated = false;
            }
            return this.IsValidated = true;
        }

        /// <summary>
        /// 验证是否通过
        /// </summary>
        [Browsable(false), Category("验证"), Description("获取该控件是否已验证通过")]
        public bool IsValidated
        {
            get;
            set;
        }

        /// <summary>
        /// 设置与内容匹配的正则表达式
        /// </summary>
        [Browsable(true), Category("验证"), Description("设置要匹配的正则表达式")]
        public string Expression
        {
            get;
            set;
        }

        /// <summary>
        /// 设置验证不通过的错误提示信息
        /// </summary>
        [Browsable(true), Category("验证"), Description("设置验证未通过时提示的内容")]
        public string SetError
        {
            get;
            set;
        }
        #endregion
    }
}
